'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { Tabs, List, Typography, Tag, Space, Pagination, Button, Spin, Empty, Card, Modal } from 'antd';
import { FileImageOutlined, SendOutlined, CloudDownloadOutlined } from '@ant-design/icons';
import AdminLayout from '../AdminLayout';

const { Title, Text, Paragraph } = Typography;

interface RecordItem {
  id?: string;
  _id?: string;
  type?: string;
  recordType?: 'txt2img' | 'img2img' | 'extra-single-image' | string;
  createdAt?: string;
  request?: any;
  forwarded?: any;
  response?: any;
}

export default function CreationRecordsPage() {
  const [activeType, setActiveType] = useState<'all' | 'txt2img' | 'img2img' | 'extra-single-image'>('all');
  const [data, setData] = useState<RecordItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [sortBy, setSortBy] = useState<'createdAt'>('createdAt');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState<string>('');

  const handleImageClick = (imageData: string, mimeType: string) => {
    setPreviewImage(`data:${mimeType};base64,${imageData}`);
    setPreviewVisible(true);
  };

  const handlePreviewClose = () => {
    setPreviewVisible(false);
    setPreviewImage('');
  };

  const fetchData = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      params.set('page', String(page));
      params.set('pageSize', String(pageSize));
      params.set('sortBy', sortBy);
      params.set('sortOrder', sortOrder);
      if (activeType !== 'all') params.set('type', activeType);

      const res = await fetch(`/api/sd/creation-records?${params.toString()}`);
      if (!res.ok) throw new Error('获取创作记录失败');
      const json = await res.json();
      const list: RecordItem[] = json.data || [];
      setData(list);
      setTotal(json.pagination?.total || list.length);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeType, page, pageSize, sortBy, sortOrder]);

  const renderItem = (item: RecordItem) => {
    const id = item.id || (item as any)._id || Math.random().toString(36).slice(2);
    const type = item.recordType || item.type || 'unknown';
    const createdAt = item.createdAt ? new Date(item.createdAt).toLocaleString() : '';

    // 从响应中取第一张 base64 预览
    let previewBase64: string | undefined;
    let mime = 'image/png';
    if (type === 'txt2img' || type === 'img2img') {
      const images = item.response?.images as string[] | undefined;
      if (images && images.length > 0) previewBase64 = images[0];
    } else if (type === 'extra-single-image') {
      const img = item.response?.image as string | undefined;
      if (img) previewBase64 = img;
    }

    return (
      <List.Item key={id}
        actions={[
          <Tag color={type === 'txt2img' ? 'blue' : type === 'img2img' ? 'purple' : 'gold'} key="type">{type}</Tag>,
          <Text type="secondary" key="time">{createdAt}</Text>
        ]}
      >
        <List.Item.Meta
          avatar={<FileImageOutlined style={{ fontSize: 24, color: '#00ff00' }} />}
          title={<span style={{ color: '#00ff00', fontWeight: 500, fontSize: '14px' }}>记录ID: {id}</span>}
          description={
            <div>
              <Space direction="vertical" size={4} style={{ width: '100%' }}>
                <Text ellipsis={{ tooltip: JSON.stringify(item.request) }}>请求: {JSON.stringify(item.request)}</Text>
                <Text ellipsis={{ tooltip: JSON.stringify(item.forwarded) }}>转发: {JSON.stringify(item.forwarded)}</Text>
              </Space>
            </div>
          }
        />
        {previewBase64 ? (
          <img 
            src={`data:${mime};base64,${previewBase64}`} 
            alt="preview" 
            style={{ 
              width: 120, 
              height: 120, 
              objectFit: 'cover', 
              borderRadius: 8, 
              cursor: 'pointer',
              transition: 'transform 0.2s ease'
            }} 
            onClick={() => handleImageClick(previewBase64, mime)}
            onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.05)'}
            onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
          />
        ) : (
          <div style={{ width: 120, height: 120, background: '#222', color: '#aaa', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>无预览</div>
        )}
      </List.Item>
    );
  };

  return (
    <AdminLayout>
      <div style={{ padding: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <Title level={2} style={{ margin: 0 }}>创作记录</Title>
          <Space>
            <Button icon={<CloudDownloadOutlined />} onClick={() => setActiveType('all')}>全部</Button>
            <Button onClick={() => setActiveType('txt2img')}>文生图</Button>
            <Button onClick={() => setActiveType('img2img')}>图生图</Button>
            <Button onClick={() => setActiveType('extra-single-image')}>后期处理</Button>
          </Space>
        </div>

        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: 48 }}>
            <Spin size="large" />
          </div>
        ) : data.length === 0 ? (
          <Empty description={<span style={{ color: '#fff' }}>暂无创作记录</span>} />
        ) : (
          <>
            <Card>
              <List
                itemLayout="horizontal"
                dataSource={data}
                renderItem={renderItem}
              />
            </Card>

            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
              <Pagination
                current={page}
                pageSize={pageSize}
                total={total}
                showSizeChanger
                onChange={(p, ps) => {
                  setPage(p);
                  setPageSize(ps);
                }}
              />
            </div>
          </>
        )}
      </div>
      
      {/* 图片预览Modal */}
      <Modal
        open={previewVisible}
        onCancel={handlePreviewClose}
        footer={null}
        width="80%"
        style={{ maxWidth: '800px' }}
        centered
        title="图片预览"
      >
        <div style={{ textAlign: 'center' }}>
          <img
            src={previewImage}
            alt="预览图片"
            style={{
              maxWidth: '100%',
              maxHeight: '70vh',
              objectFit: 'contain'
            }}
          />
        </div>
      </Modal>
    </AdminLayout>
  );
}